package com.auhaix.service;

import com.auhaix.common.UserException;
import com.auhaix.entity.User;
import com.auhaix.common.ResponseEnum;
import com.auhaix.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/**
 * Author: Auhaix
 * E-mail: xh@qiandw.com
 * Description:
 * CreatedTime: 2017/7/26 15:36
 * Modified by:
 */
@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    /**
     * 事务回滚测试
     * 1、Spring默认只对运行时异常进行事务回滚；
     * 2、可以通过事务注解改变普通异常进行事务回滚
     *
     * @throws Exception
     */
    @Transactional(rollbackOn = Exception.class)

    public void insertTwo() throws Exception {

        User userA = new User();
        userA.setDuty("C岗位");
        userA.setAge(18);
        userA.setName("小龙女");
        userRepository.save(userA);

        User userB = new User();
        userB.setName("李莫愁");
        userB.setDuty("A岗位");
        userB.setAge(getIntAge());
        userRepository.save(userB);

        User userC = userRepository.getOne(1);
        userC.setAge(88);
        userRepository.save(userC);
    }

    private int getIntAge() throws RuntimeException {
        try {
            int a = 5;
            int b = 0;
            return a / b;
        } catch (Exception e) {
            throw new UserException(ResponseEnum.UN_KNOWN_ERROR);
        }
    }

    public void promotion(Integer id, String duty) throws UserException {
        User user = userRepository.getOne(id);
        Integer age = user.getAge();
        if (age < 25) {
            throw new UserException(ResponseEnum.YOU_ARE_SO_YOUNG);
        } else if (age < 30 && duty.contains("经理")) {
            throw new UserException(ResponseEnum.YOU_NEED_MORE_STUDY);
        } else if (age > 60) {
            throw new UserException(ResponseEnum.YOU_ARE_TOO_OLD);
        }
        user.setDuty(duty);
        userRepository.save(user);
    }
}
